<template>
  <div class="game-container">
    <!-- 头部资源显示 -->
    <header class="header">
      <div class="resources">
        <div class="resource"><i class="fas fa-coins"></i> {{ gold }}</div>
        <div class="resource"><i class="fas fa-tint"></i> {{ water }}</div>
        <div class="resource"><i class="fas fa-sun"></i> {{ sun }}</div>
      </div>
      <button class="menu-btn" @click="toggleMenu"><i class="fas fa-bars"></i></button>
    </header>

    <!-- 天气横幅 -->
    <div class="weather-banner">{{ weather }}</div>

    <!-- 游戏主区域 -->
    <main class="game-main">
      <!-- 农场区域 -->
      <section class="farm-area" v-if="currentView === 'farm'">
        <div class="farm-grid">
          <div v-for="(cell, index) in farmGrid" :key="index" class="farm-cell"
               :class="{ 'has-plant': cell.plant, 'watered': cell.watered, 'dead': cell.dead }"
               @click="handleCellClick(index)">
            <div v-if="cell.plant" class="plant">
              <i :class="getPlantIcon(cell.plant)"></i>
              <div class="plant-stage">{{ cell.stage }}/{{ maxStage }}</div>
            </div>
          </div>
        </div>
      </section>

      <!-- 商店区域 -->
      <section class="shop-area" v-else-if="currentView === 'shop'">
        <h2>商店</h2>
        <div class="shop-items">
          <div v-for="item in shopItems" :key="item.id" class="shop-item"
               @click="buyItem(item)">
            <i :class="item.icon"></i>
            <div class="item-name">{{ item.name }}</div>
            <div class="item-price">{{ item.price }} <i class="fas fa-coins"></i></div>
          </div>
        </div>
      </section>

      <!-- 背包区域 -->
      <section class="backpack-area" v-else-if="currentView === 'backpack'">
        <h2>背包</h2>
        <div class="filter-buttons">
          <button :class="{ 'active': filterType === 'all' }" @click="filterType = 'all'"></button>
          <button :class="{ 'active': filterType === 'seeds' }" @click="filterType = 'seeds'"></button>
          <button :class="{ 'active': filterType === 'tools' }" @click="filterType = 'tools'"></button>
        </div>
        <div class="backpack-items">
          <div v-for="item in filteredItems" :key="item.id" class="backpack-item"
               @click="useItem(item)">
            <i :class="item.icon"></i>
            <div class="item-name">{{ item.name }}</div>
            <div class="item-count">x{{ item.count }}</div>
          </div>
        </div>
      </section>
    </main>

    <!-- 底部导航 -->
    <nav class="bottom-nav">
      <button :class="{ 'active': currentView === 'farm' }" @click="currentView = 'farm'">
        <i class="fas fa-tractor"></i>
        <span>农场</span>
      </button>
      <button :class="{ 'active': currentView === 'shop' }" @click="currentView = 'shop'">
        <i class="fas fa-shopping-cart"></i>
        <span>商店</span>
      </button>
      <button :class="{ 'active': currentView === 'backpack' }" @click="currentView = 'backpack'">
        <i class="fas fa-backpack"></i>
        <span>背包</span>
      </button>
    </nav>

    <!-- 菜单弹窗 -->
    <div class="modal" v-if="menuOpen">
      <div class="modal-content">
        <h2>菜单</h2>
        <button @click="toggleSettings"><i class="fas fa-cog"></i> 设置</button>
        <button @click="showNotification('游戏已保存！')"><i class="fas fa-save"></i> 保存游戏</button>
        <button @click="resetGame"><i class="fas fa-redo"></i> 重置游戏</button>
        <button @click="goToRuins"><i class="fas fa-monument"></i> 遗迹探索</button>
        <button @click="toggleMenu"><i class="fas fa-times"></i> 关闭</button>
      </div>
    </div>

    <!-- 设置面板 -->
    <div class="modal" v-if="settingsOpen">
      <div class="modal-content">
        <h2>设置</h2>
        <div class="setting-item">
          <label>音乐</label>
          <input type="checkbox" v-model="settings.music">
        </div>
        <div class="setting-item">
          <label>音效</label>
          <input type="checkbox" v-model="settings.soundEffects">
        </div>
        <div class="setting-item">
          <label>自动保存</label>
          <input type="checkbox" v-model="settings.autoSave">
        </div>
        <button @click="toggleSettings"><i class="fas fa-times"></i> 关闭</button>
      </div>
    </div>

    <!-- 通知系统 -->
    <div class="notification" v-if="notification.show">
      {{ notification.message }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

// 路由
const router = useRouter();

// 游戏状态
const gold = ref(100);
const water = ref(50);
const sun = ref(75);
const seeds = ref([
  { id: 1, name: '小麦', count: 5, icon: 'fas fa-wheat-awn', growthTime: 3000, value: 10 },
  { id: 2, name: '胡萝卜', count: 3, icon: 'fas fa-carrot', growthTime: 4500, value: 15 },
  { id: 3, name: '土豆', count: 2, icon: 'fas fa-seedling', growthTime: 6000, value: 20 }
]);
const maxStage = 3;
const farmGrid = ref(Array(9).fill().map(() => ({
  plant: null,
  stage: 0,
  watered: false,
  dead: false,
  plantedTime: 0
})));
const weather = ref('晴朗');
const settings = ref({
  music: true,
  soundEffects: true,
  autoSave: true
});
const backpack = ref([
  ...seeds.value,
  { id: 4, name: '水壶', type: 'tools', count: 1, icon: 'fas fa-tint-slash', uses: 10 },
  { id: 5, name: '肥料', type: 'tools', count: 2, icon: 'fas fa-poo', uses: 5 }
]);

// UI 状态
const currentView = ref('farm');
const menuOpen = ref(false);
const settingsOpen = ref(false);
const filterType = ref('all');
const notification = ref({
  show: false,
  message: ''
});

// 商店物品
const shopItems = ref([
  { id: 1, name: '小麦种子', type: 'seeds', price: 5, icon: 'fas fa-wheat-awn' },
  { id: 2, name: '胡萝卜种子', type: 'seeds', price: 8, icon: 'fas fa-carrot' },
  { id: 3, name: '土豆种子', type: 'seeds', price: 12, icon: 'fas fa-seedling' },
  { id: 4, name: '水壶', type: 'tools', price: 20, icon: 'fas fa-tint-slash' },
  { id: 5, name: '肥料', type: 'tools', price: 15, icon: 'fas fa-poo' }
]);

// 计算属性 - 过滤背包物品
const filteredItems = computed(() => {
  if (filterType.value === 'all') return backpack.value;
  return backpack.value.filter(item => item.type === filterType.value);
});

// 方法
function toggleMenu() {
  menuOpen.value = !menuOpen.value;
  if (menuOpen.value) settingsOpen.value = false;
}

// 跳转到遗迹探索页面
function goToRuins() {
  router.push({
    path: '/pages/ruins/ruins',
    query: {
      funds: gold.value,
      food: water.value
    }
  });
  toggleMenu();
}

function toggleSettings() {
  settingsOpen.value = !settingsOpen.value;
  if (settingsOpen.value) menuOpen.value = false;
}

function showNotification(message) {
  notification.value.message = message;
  notification.value.show = true;
  setTimeout(() => {
    notification.value.show = false;
  }, 3000);
}

function handleCellClick(index) {
  const cell = farmGrid.value[index];
  if (cell.plant) {
    // 检查是否可以收获
    if (cell.stage >= maxStage) {
      harvestPlant(index);
    } else if (!cell.watered) {
      waterPlant(index);
    } else {
      showNotification('作物正在生长中...');
    }
  } else {
    // 种植作物
    plantSeed(index);
  }
}

function getPlantIcon(plantId) {
  const seed = seeds.value.find(s => s.id === plantId);
  return seed ? seed.icon : 'fas fa-seedling';
}

function plantSeed(index) {
  // 简化版本：总是种植第一个可用的种子
  const seed = seeds.value.find(s => s.count > 0);
  if (!seed) {
    showNotification('没有可用的种子了！');
    return;
  }

  seed.count--;
  farmGrid.value[index] = {
    plant: seed.id,
    stage: 1,
    watered: true,
    dead: false,
    plantedTime: Date.now()
  };
  showNotification(`已种植 ${seed.name}`);
}

function waterPlant(index) {
  if (water.value <= 0) {
    showNotification('没有水了！');
    return;
  }

  farmGrid.value[index].watered = true;
  water.value--;
  showNotification('已浇水');
}

function harvestPlant(index) {
  const cell = farmGrid.value[index];
  const seed = seeds.value.find(s => s.id === cell.plant);
  if (seed) {
    gold.value += seed.value;
    showNotification(`收获了 ${seed.name}，获得 ${seed.value} 金币`);
  }

  // 重置格子
  farmGrid.value[index] = {
    plant: null,
    stage: 0,
    watered: false,
    dead: false,
    plantedTime: 0
  };
}

function buyItem(item) {
  if (gold.value < item.price) {
    showNotification('金币不足！');
    return;
  }

  gold.value -= item.price;
  const existingItem = backpack.value.find(i => i.id === item.id);
  if (existingItem) {
    existingItem.count++;
  } else {
    backpack.value.push({...item, count: 1});
  }
  showNotification(`已购买 ${item.name}`);
}

function useItem(item) {
  showNotification(`使用了 ${item.name}`);
  // 在这里实现物品使用逻辑
  if (item.type === 'tools') {
    item.uses--;
    if (item.uses <= 0) {
      const index = backpack.value.findIndex(i => i.id === item.id);
      if (index !== -1) backpack.value.splice(index, 1);
    }
  }
}

function updateWeather() {
  const weathers = ['晴朗', '多云', '下雨', '大风', '冰雹'];
  weather.value = weathers[Math.floor(Math.random() * weathers.length)];

  // 根据天气影响游戏
  switch(weather.value) {
    case '下雨':
      water.value += 10;
      showNotification('下雨了，水资源增加！');
      break;
    case '晴朗':
      sun.value += 5;
      break;
    case '大风':
      // 有几率吹走作物
      break;
    case '冰雹':
      // 有几率损坏作物
      break;
  }
}

function resetGame() {
  if (confirm('确定要重置游戏吗？所有进度将丢失！')) {
    gold.value = 100;
    water.value = 50;
    sun.value = 75;
    farmGrid.value = Array(9).fill().map(() => ({
      plant: null,
      stage: 0,
      watered: false,
      dead: false,
      plantedTime: 0
    }));
    showNotification('游戏已重置');
  }
}

// 游戏循环
function gameLoop() {
  // 更新作物生长
  farmGrid.value.forEach((cell, index) => {
    if (cell.plant && !cell.dead) {
      const now = Date.now();
      const growthTime = seeds.value.find(s => s.id === cell.plant)?.growthTime || 3000;

      // 检查是否应该生长
      if (now - cell.plantedTime > growthTime && cell.stage < maxStage) {
        cell.stage++;
        cell.plantedTime = now;
        showNotification(`作物生长到了第 ${cell.stage} 阶段`);
      }

      // 检查是否缺水死亡
      if (!cell.watered && now - cell.plantedTime > growthTime / 2) {
        cell.dead = true;
        showNotification('作物缺水死亡了！');
      }
    }
  });

  // 随机增加资源
  if (Math.random() < 0.1) {
    gold.value += 1;
  }
  if (Math.random() < 0.05) {
    water.value += 1;
  }
  if (Math.random() < 0.08) {
    sun.value += 1;
  }
}

// 生命周期
onMounted(() => {
  // 初始化游戏
  updateWeather();
  setInterval(gameLoop, 1000);
  setInterval(updateWeather, 30000);

  // 加载保存的游戏状态（如果有）
  const savedState = localStorage.getItem('farmGameState');
  if (savedState) {
    try {
      const state = JSON.parse(savedState);
      gold.value = state.gold;
      water.value = state.water;
      sun.value = state.sun;
      farmGrid.value = state.farmGrid;
      settings.value = state.settings;
      backpack.value = state.backpack;
      showNotification('已加载保存的游戏');
    } catch (e) {
      console.error('加载游戏状态失败', e);
    }
  }

  // 自动保存
  if (settings.value.autoSave) {
    setInterval(() => {
      const state = {
        gold: gold.value,
        water: water.value,
        sun: sun.value,
        farmGrid: farmGrid.value,
        settings: settings.value,
        backpack: backpack.value
      };
      localStorage.setItem('farmGameState', JSON.stringify(state));
    }, 60000);
  }
});
</script>